﻿using System;
using System.Net;
using System.Collections;
using System.Drawing;
using System.Data;
using System.Data.SqlClient;
using TradePublish.Common;
using Winista.Text.HtmlParser;
using Winista.Text.HtmlParser.Filters;
using Winista.Text.HtmlParser.Util;
 using TradePublish.Exceptions;
using System.Text.RegularExpressions;
using TradePublish.Entity;
using System.Collections.Generic;
using System.Threading;
using log4net;
using System.Reflection;
using System.Web;
using System.Text;
namespace TradePublish.Service
{
    /// <summary>
    /// 异议状态查询的工具类
    /// </summary>
    public class DissentStatusSearchTMManager
    {
        public int classNo;//国际分类号
        public String regNo;//待查的商标注册号 
        public Int32 IntCls;//国际分类号
        ILog log = null;

        CookieContainer logc = null;
        public DissentStatusSearchTMManager()
        {
            log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        }

        /// <summary>
        /// 异议查询，是否匹配上，异常自己处理。
        /// </summary>
        /// </param>
        /// <returns></returns>
        public Boolean isMatched()
        {
            String trueUrl = "http://sbcx.saic.gov.cn/trade/servlet?Search=FL_REG&RegNO=" + regNo + "&IntCls=" + IntCls;
            while (true)
            {
                try
                {
                    if (logc == null)
                    { //登录首页
                        this.logc = getLoginCookie();
                    }
                    if (this.logc == null)
                    {
                        Thread.Sleep(1000);
                        log.Info("进行异议状态查询，登录异常"); //---------登录失败，抛出异常，结束。 
                        continue;
                    }
                    #region  开始进行异议状态查询，获得html代码
                    GraspHTML grasphtml = new GraspHTML();
                    String source = grasphtml.getHTMLCode(trueUrl, this.logc);
                    if (source == null || source.Equals("") || source.IndexOf("请从首页访问") >= 0)
                    {
                        Thread.Sleep(1000);
                        this.logc = getLoginCookie();
                        log.Info("进行异议状态查询，html为null，重新采集."); //---------登录失败，抛出异常，结束。
                        continue;
                    }
                    #endregion

                    #region 将商标流程更新到商标详情中
                    Parser parser = Parser.CreateParser(source, "UTF-8"); ;
                    NodeFilter filter = new HasAttributeFilter("class", "tbg2");
                    NodeList nodes = parser.ExtractAllNodesThatMatch(filter);
                    List<String> urls = new List<String>();
                    if (nodes != null && nodes.Count > 0)
                    {
                        Parser parserT = Parser.CreateParser(nodes[0].ToHtml(), "UTF-8"); ;
                        NodeFilter filterT = new NodeClassFilter(typeof(Winista.Text.HtmlParser.Tags.TableRow));
                        NodeList nodesT = parserT.ExtractAllNodesThatMatch(filterT);
                        if (nodesT != null && nodesT.Count >= 4)
                        {
                            StringBuilder sylc = new StringBuilder();
                            for (int j = 4; j < nodesT.Size(); j++)
                            {
                                Winista.Text.HtmlParser.Tags.TableRow tag = (Winista.Text.HtmlParser.Tags.TableRow)(nodesT.ElementAt(j) is ITag ? nodesT.ElementAt(j) as ITag : null);
                                if (tag != null && !tag.IsEndTag() && tag.Children.Count > 3)
                                {
                                    if (j > 4)
                                    {
                                        sylc.Append("--->");
                                    }
                                    sylc.Append(tag.Children[1].ToPlainTextString().Trim()).Append("(").Append(tag.Children[3].ToPlainTextString().Trim()).Append(")");
                                }
                            }
                            BrandInfoManager brandInfoManager = new BrandInfoManager();
                            //更新商标的使用流程字段,内部异常自己处理
                            brandInfoManager.updateSylc(regNo, sylc.ToString());
                        }
                    }
                    #endregion

                    #region 根据html看看是否匹配
                    MatchCollection mc = Regex.Matches(source, @"收到异议申请或补充材料,待审", RegexOptions.IgnoreCase);
                    if (mc.Count > 0)
                    {
                        return true;//匹配到
                    }
                    else
                    {
                        return false;//未匹配到
                    }
                    #endregion
                }
                catch (Exception e)
                {
                    log.Error("进行异议状态查询，异常.", e);
                    Thread.Sleep(1000);
                    continue;
                }
            }
        }


        /// <summary>
        /// 是否匹配上，异常自己处理。
        /// </summary>
        /// </param>
        /// <returns></returns>
        public Boolean isMatched(int category, Int32 issue)
        {
            String trueUrl = "http://sbcx.saic.gov.cn/trade/servlet?Search=FL_REG&RegNO=" + regNo + "&IntCls=" + IntCls;
            while (true)
            {
                try
                {
                    if (logc == null)
                    { //登录首页
                        this.logc = getLoginCookie();
                    }
                    if (this.logc == null)
                    {
                        Thread.Sleep(1000);
                        log.Info("进行转让待审状态查询，登录异常"); //---------登录失败，抛出异常，结束。 
                        continue;
                    }
                    #region  开始进行异议状态查询，获得html代码
                    GraspHTML grasphtml = new GraspHTML();
                    String source = grasphtml.getHTMLCode(trueUrl, this.logc);
                    if (source == null || source.Equals("") || source.IndexOf("请从首页访问") >= 0)
                    {
                        Thread.Sleep(1000);
                        this.logc = getLoginCookie();
                        log.Info("进行异议状态查询，html为null，重新采集."); //---------登录失败，抛出异常，结束。
                        continue;
                    }
                    #endregion



                    #region 根据html看看是否匹配
                    //1商标注册公告
                    //    初步审定（<期号>）
                    //   判断条件：状态查询中，含有“初步审定”，且后面的期号跟本期相同。

                    //2商标转让公告
                    //    判断条件：状态查询中，含有“转让待审中”

                    //3变更许可人/被许可人名义公告
                    //    判断条件：状态查询中，含有“许可合同备案待审中”或“变更待审中”

                    //4商标注册证无效公告

                    //5注册商标注销公告
                    //    判断条件：状态查询中，含有“商标已无效”

                    //6商标异议公告
                    //     收到异议申请或补充材料,待审
                    //   判断条件：状态查询中，含有“收到异议申请或补充材料,待审”文字

                    //7未续展商标注销公告
                    //    判断条件：状态查询中，含有“商标已无效”

                    String ppwz = "无";
                    if (category == 1)
                    {
                        ppwz = @"初步审定（" + issue + "）";
                    }
                    else if (category == 2)
                    {
                        ppwz = @"转让待审中";
                    }

                    else if (category == 3)
                    {
                        ppwz = @"转让待审中";
                    }

                    else if (category == 5 || category == 7)
                    {
                        ppwz = @"商标已无效";
                    }

                    else if (category == 6)
                    {
                        ppwz = @"收到异议申请或补充材料,待审";
                    }


                    MatchCollection mc = Regex.Matches(source, ppwz, RegexOptions.IgnoreCase);
                    if (mc.Count > 0)
                    {
                        return true;//匹配到
                    }
                    else
                    {
                        return false;//未匹配到
                    }
                    #endregion
                }
                catch (Exception e)
                {
                    log.Error("进行异议状态查询，异常.", e);
                    Thread.Sleep(1000);
                    continue;
                }
            }
        }



        #region －子函数－获得登录的cookie
        private CookieContainer getLoginCookie()
        {
            CookieContainer cc = null;
            #region 登录，得到cookie
            GraspHTML grasphtml = new GraspHTML();

            cc = grasphtml.getLoginCookie(Global.LoginURL);
            if (grasphtml.getException().Length > 0)
            {
                //发生异常,暂停后重试
                cc = null;
            }
            #endregion
            return cc;
        }
        #endregion

        #region   －子函数－ 移除不必要的HTML代码	 RemoveCode()
        private String RemoveCode(String inName)
        {/*移除不必要的的代码*/
            if (inName != null && inName.Length > 0)
            {
                inName = inName.Replace("\r", "");
                inName = inName.Replace("\n", "");
                inName = inName.Replace("\t", "");
                inName = inName.Replace("&nbsp;", " ");
            }
            return inName;

        }
        #endregion


    }
}
